import type { ProcessBlock, BlockProcessor, PreBlock } from '../types';
import { isEmptyRow } from '../util';

const isBlockBegin = (_row: PreBlock) => false;

const processBlock: ProcessBlock = (pbs) => {
  pbs.push({ type: 'row', value: '' });

  const result: PreBlock[] = [];

  for (let i = 0; i < pbs.length - 1; ) {
    const b0 = pbs[i];
    const b1 = pbs[i + 1];
    if (b0.type === 'row' && b1.type === 'row') {
      if (!isEmptyRow(b0)) {
        if (/^-{3,}$/.test(b1.value)) {
          result.push({ type: 'heading', level: 2, row: b0 });
          i += 2;
          continue;
        } else if (/^={3,}$/.test(b1.value)) {
          result.push({ type: 'heading', level: 1, row: b0 });
          i += 2;
          continue;
        } else {
          result.push(b0);
          i += 1;
        }
      } else {
        result.push(b0);
        i += 1;
      }
    } else if (b1.type !== 'row') {
      result.push(b0, b1);
      i += 2;
    } else {
      result.push(b0);
      i += 1;
    }
  }

  return result;
};

const setextHeadingProcessor: BlockProcessor = {
  isBlockBegin,
  process: processBlock,
};

export default {
  processor: setextHeadingProcessor,
};
